package io.github.hadyang.leetcode.offer;

import io.github.hadyang.leetcode.ListNode;
import org.junit.Test;

/** @author haoyang.shi */
public class RevertLink {

  @Test
  public void test() {
    ListNode head1 = new ListNode(2);
    ListNode head2 = new ListNode(4);
    ListNode head3 = new ListNode(3);
    head1.next = head2;
    head2.next = head3;

    ListNode reverseList = ReverseList(head1);

    while (reverseList != null) {
      System.out.println(reverseList.val);
      reverseList = reverseList.next;
    }
  }

  public ListNode ReverseList(ListNode head) {
    if (head == null || head.next == null) {
      return head;
    }

    ListNode pre = head, cur = head.next, next;
    pre.next = null;

    while (cur != null) {
      next = cur.next;
      cur.next = pre;

      pre = cur;
      cur = next;
    }

    return pre;
  }
}
